package framework;

import framework.webclient.ProxyData;
import framework.webserver.RestServer;
import framework.webserver.ServiceStore;

public abstract class AbstractApplication {
	
	abstract protected DomainService getService();
	abstract protected Client getClient();
	
	private String account = "";
	private String password = "";
	private ProxyData proxy = null;
	private FrameworkUi frameworkUi = new JavaFxFrameworkUi();
	
	protected void start() {
		if (isSilientLogin()) {
			startApplication(account, password, proxy);
		}
		else {
			frameworkUi.createLoginUi(new LoginHandler() {
				@Override
				public void onOK(String account, String password,
						ProxyData proxy) {
					startApplication(account, password, proxy);
				}
			});
		}
	}

	
	private boolean isSilientLogin() {
		return !this.getService().isOnline();
	}
	
	private void startApplication(final String account,
			final String password, final ProxyData proxy) {
		
		frameworkUi = new JavaFxFrameworkUi();
		frameworkUi.setLoginStatusVisible(true);
		
		new Thread() {
			@Override
			public void run() {
				final DomainService service = getService();
				service.initialize(account, password, proxy);
				startWebServer(service);
				
				frameworkUi.setLoginStatusVisible(false);
				launchClient(service);
			}			
		}.start();
	}
	
	private void startWebServer(final DomainService service) {
		ServiceStore.put(service.getServiceName(), service);
		new RestServer(service).start();
	}
	
	private void launchClient(final DomainService service) {
		Client client = getClient();
		if (client != null) {
			client.initialize(service);
		}
	}
}
